#!/usr/bin/python

CONFIG_FILE = '../config.txt'
SUBSCRIBE_INTERVAL = 0.25
SUBSCRIBE_LIMIT = 400

SRC_ACCOUNT = 0
DST_ACCOUNT = 2
MOVE_CRITERIA = 'm.*@g.*mail\.com'
#MOVE_CRITERIA = 'n.*@g.*mail\.com'
#MOVE_CRITERIA = 'na.*@g.*mail\.com'
#MOVE_CRITERIA = 'me.*@g.*mail\.com'
#MOVE_CRITERIA = 'ma.*@g.*mail\.com'
#MOVE_CRITERIA = 're.*@g.*mail\.com'
#MOVE_CRITERIA = 'ra.*@g.*mail\.com'
#MOVE_CRITERIA = 'q.*@g.*mail\.com'
#MOVE_CRITERIA = 'p.*@g.*mail\.com'
#MOVE_CRITERIA = 'ph.*@g.*mail\.com'
#MOVE_CRITERIA = 'se.*@g.*mail\.com'
#MOVE_CRITERIA = 'la.*@g.*mail\.com'
#MOVE_CRITERIA = 'sa.*@g.*mail\.com'
#MOVE_CRITERIA = 'pe.*@g.*mail\.com'
#MOVE_CRITERIA = 'pa.*@g.*mail\.com'
#MOVE_CRITERIA = 'o.*@g.*mail\.com'
#MOVE_CRITERIA = 'ka.*@g.*mail\.com'
#MOVE_CRITERIA = 'ja.*@g.*mail\.com'
#MOVE_CRITERIA = 'ha.*@g.*mail\.com'
#MOVE_CRITERIA = 'ga.*@g.*mail\.com'
#MOVE_CRITERIA = 'i.*@g.*mail\.com'

import re
import sys
import time

sys.path.append('../../../misc')
import xmpppy as xmpp


def read_ConfigFile():
	"Read configuration settings for all accounts"
	global configs
	configs = {}
	for line in open(CONFIG_FILE).readlines():
		line = line.strip()
		if len(line) > 0 and not line.startswith('#'):	# Not a blank line or a comment
			key, value = line.split(':')
			key = key.strip().lower()
			value = value.strip()
			if configs.has_key(key):
				configs[key].append(value);
			else:
				configs[key] = [value]


def start_Connection(accIndex):
	domain = configs['domain'][accIndex]
	username = configs['username'][accIndex]
	password = configs['password'][accIndex]
	url = configs['url'][accIndex]
	port = int(configs['port'][accIndex])

	print 'ACTION: connecting %s@%s to server' % (username, domain)
	client = xmpp.Client(domain, debug=[])
	client.connect(server = (url, port))
	client.auth(username, password)
	client.sendInitPresence()
	return client



def move_Contacts(srcBot, dstBot, MOVE_REGEXP):
	moveRE = re.compile(MOVE_REGEXP)
	srcRoster = srcBot.getRoster()
	dstRoster = dstBot.getRoster()
	admins = configs['admin']
	print 'WARNING: These addresses will be excluded from moving:'
	print admins
	moveLog = open('moved.log', 'at')
	moveCount = 0
	for contact in srcRoster.getItems():
		if moveRE.match(contact) and contact not in admins:
			moveCount += 1
			print 'ACTION: moving', contact
			dstRoster.Subscribe(contact)
			srcRoster.Unsubscribe(contact)
			srcRoster.Unauthorize(contact)
			srcRoster.delItem(contact)
			moveLog.write('%s\n' % contact)
			time.sleep(SUBSCRIBE_INTERVAL)
			if moveCount == SUBSCRIBE_LIMIT:
				break
	print 'SUMMARY: Total contacts moved:', moveCount
	moveLog.close()


#def email_Contacts(contactFile):
#	for filename in open(contactFile).readlines():
#		filename = filename.strip()
		

if __name__ == '__main__':
	read_ConfigFile()
	srcBot = start_Connection(SRC_ACCOUNT)
	dstBot = start_Connection(DST_ACCOUNT)
	move_Contacts(srcBot, dstBot, MOVE_CRITERIA)
#	subscribe_Contacts(sys.argv[1])
#	email_Contacts(sys.argv[1])		
